package com.losdun.points.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.points.domain.PointsRecord;
import com.losdun.points.domain.UserPoints;
import com.losdun.points.enums.PointsSourceTypeEnum;
import com.losdun.points.enums.PointsTypeEnum;
import com.losdun.points.mapper.PointsRecordMapper;
import com.losdun.points.service.PointsRecordService;
import com.losdun.points.service.UserPointsService;
import com.losdun.weixin.domain.WechatUser;
import com.losdun.weixin.service.WechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author sword.ye
 * @date 2025/4/13
 **/
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements PointsRecordService {
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private UserPointsService userPointsService;

    @Override
    public List<PointsRecord> queryPointsRecordList(PointsRecord pointsRecord) {
        return baseMapper.selectList(new QueryWrapper<>(pointsRecord).orderByDesc("create_time"));
    }

    @Override
    public void updateUserPointsRecord(Long userId, Integer sourceType, Integer pointsType, Integer points, String remark) {
        WechatUser userEntity = wechatUserService.getById(userId);
        UserPoints userPoints = userPointsService.getById(userId);
        PointsRecord record = new PointsRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setSourceType(sourceType);
        record.setUserType(userEntity.getUserType());
        record.setUserId(userEntity.getId());
        record.setUserName(userEntity.getPhone());
        record.setPoint(points);
        record.setPointType(pointsType);
        record.setPrePoint(userPoints.getAvailablePoints());
        int nextPoint;
        if (PointsTypeEnum.ADD.getCode().equals(pointsType)) {
            nextPoint = userPoints.getAvailablePoints() + points;
        } else {
            nextPoint = Math.max(userPoints.getAvailablePoints() - points,0);
        }
        record.setNextPoint(nextPoint);
        record.setReason(remark);
        baseMapper.insert(record);

        userPointsService.updateAvaliablePoints(userEntity.getId(),nextPoint);
    }
}
